package win.ganbo.softwareFive.listener;

import java.util.Map;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;

import org.jasig.cas.client.util.AbstractCasFilter;
import org.jasig.cas.client.validation.Assertion;

import win.ganbo.softwareFive.utils.MemberSession;

/**
 * 自定义session监听器，在cas服务端返回消息时自定义存入session
 *                     
 * @Author: 甘波
 * @Email: ganbo@gyiragon.com
 * @2016年12月22日 下午5:03:10
 */
@WebListener
public class CasSessionListener implements HttpSessionAttributeListener {

    private static String MEMBER_SESSION_NAME = "memberSession";

    public void attributeAdded(HttpSessionBindingEvent event) {
        String key = event.getName();

        //        System.out.println("key====>" + key);
        if (key.equals(AbstractCasFilter.CONST_CAS_ASSERTION)) {

            Assertion as = (Assertion) event.getSession()
                .getAttribute(AbstractCasFilter.CONST_CAS_ASSERTION);
            Map<String, Object> map = as.getPrincipal().getAttributes();

            Member member = new Member();
            member.setId(Integer.parseInt(map.get("id").toString()));
            member.setName(map.get("name") + "");
            member.setPassword((String) map.get("password"));
            member.setImPassword(map.get("imPassword") + "");

            MemberSession memberSession = new MemberSession();
            if (member != null) {
                memberSession.setMember(member);
            }
            event.getSession().setAttribute(MEMBER_SESSION_NAME, memberSession);

            //            String auther = "";
            //            try {
            //                                auther = URLDecoder.decode((String) map.get("auther"), "UTF-8");
            //            } catch (UnsupportedEncodingException e) {
            //                e.printStackTrace();
            //            }

            //            HttpSession session = RequestHolder.getSession();
            //            session.setAttribute(ConstantConfig.USER_IN_SESSION, member);

        }

    }

    public void attributeRemoved(HttpSessionBindingEvent arg0) {
    }

    public void attributeReplaced(HttpSessionBindingEvent arg0) {
    }

}
